from alibabacloud_bailian20231229.client import Client as bailian20231229Client
from alibabacloud_tea_openapi.client import Client as OpenApiClient
from alibabacloud_credentials.client import Client as CredentialClient
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_tea_util import models as util_models
import hashlib
from app.database.db_setup import Base 
from sqlalchemy import Column, Integer, String, ForeignKey,SmallInteger
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base

class Sample:
    def __init__(self):
        pass

    @staticmethod
    def create_client(access_key_id, access_key_secret) -> bailian20231229Client:
        """
        使用 AK 初始化账号 Client
        @return: Client
        @throws Exception
        """
        config = open_api_models.Config(
            access_key_id=access_key_id,
            access_key_secret=access_key_secret
        )
        # Endpoint 请参考 https://api.aliyun.com/product/bailian
        config.endpoint = f'bailian.cn-beijing.aliyuncs.com'
        return bailian20231229Client(config)

    @staticmethod
    def create_api_info(
        category_id: str,
        workspace_id: str,
    ) -> open_api_models.Params:
        """
        API 相关
        @param path: string Path parameters
        @return: OpenApi.Params
        """
        params = open_api_models.Params(
            # 接口名称,
            action='ApplyFileUploadLease',
            # 接口版本,
            version='2023-12-29',
            # 接口协议,
            protocol='HTTPS',
            # 接口 HTTP 方法,
            method='POST',
            auth_type='AK',
            style='ROA',
            # 接口 PATH,
            pathname=f'/{workspace_id}/datacenter/category/{category_id}',
            # 接口请求体内容格式,
            req_body_type='formData',
            # 接口响应体内容格式,
            body_type='json'
        )
        return params

    @staticmethod
    def call_api(
        access_key_id,
        access_key_secret,
        category_id,
        workspace_id,
        file_name,
        md5,
        size_in_bytes
    ):
        client = Sample.create_client(access_key_id, access_key_secret)
        params = Sample.create_api_info(category_id, workspace_id)
        # body params
        body = {}
        body['FileName'] = file_name
        body['Md5'] = md5
        body['SizeInBytes'] = size_in_bytes
        # runtime options
        runtime = util_models.RuntimeOptions()
        request = open_api_models.OpenApiRequest(
            body=body
        )
        result = client.call_api(params, request, runtime)
        return result


def calculate_file_md5(file_path):
    hash_md5 = hashlib.md5()
    with open(file_path, "rb") as f:
        for chunk in iter(lambda: f.read(4096), b""):
            hash_md5.update(chunk)
    return hash_md5.hexdigest()
class AiUploadFile(Base):
    __tablename__ = 'rk_ai_uplode_file'

    id = Column(Integer, primary_key=True, autoincrement=True, comment='ID')
    script_id = Column(Integer, nullable=False, comment='话术id')
    cat_id = Column(Integer, nullable=False, comment='分类id')
    CategoryId = Column(String(200), nullable=False, default='', comment='分类标识，可能与cat_id有重复，需确认')
    url = Column(String(255), nullable=False, default='', comment='阿里云url')
    is_set = Column(SmallInteger, nullable=False, default=0, comment='1已导入，0未导入')
    extra = Column(String(255), nullable=False, default='', comment='额外信息')
    content_type = Column(String(255), nullable=False, default='', comment='文件类型')
    size_in_bytes = Column(Integer, nullable=False, comment='文件大小')
    file_name = Column(String(255), nullable=False, default='', comment='文件名称')
    file_path = Column(String(255), nullable=False, default='', comment='文件在服务器上的相对路径')
    absolute_file_path = Column(String(255), nullable=False, default='', comment='文件在服务器上的绝对路径')
    FileUploadLeaseId = Column(String(300), nullable=False, default='', comment='文件上传租约的ID')
    FileId = Column(String(500), nullable=False, default='', comment='阿里云调用文档id')
    Parser = Column(String(300), nullable=False, default='', comment='阿里云调用文档Parser')
    md5 = Column(String(500), nullable=False, default='', comment='文件的md5的值')
    add_time = Column(Integer, nullable=False, default=0, comment='添加记录的时间')
    set_time = Column(Integer, nullable=False, default=0, comment='文档上传相关的标识，需进一步明确含义')
    